package cn.baiweigang.uu.service.dingding;

import cn.baiweigang.uu.GlobalContext;
import cn.baiweigang.uu.service.okhttp.HttpService;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

@Service
@Slf4j
public class DingService {

    @Autowired
    private HttpService httpService;

    private final static String DingUrl = "https://oapi.dingtalk.com/robot/send?";

    public void send(String text) {
        //消息体
        JSONObject body = new JSONObject();
        body.put("msgtype", "text");
        JSONPath.set(body, "text.content", text);
        //组装query参数
        Long timestamp = System.currentTimeMillis();
        String sign = sign(timestamp);
        String accessToken = GlobalContext.dbConfigCache.get("DingDing_access_token") + "";
        String url = DingUrl + "access_token=" + accessToken + "&timestamp=" + timestamp + "&sign=" + sign;

        String resp = httpService.doPost(url, null, body);
        log.info("Ding resp "+resp);
    }

    private static String sign(Long timestamp) {
        //从DB获取secret
        String secret = GlobalContext.dbConfigCache.get("DingDing_secret") + "";
        try {
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            return sign;
        } catch (Throwable e) {
            log.error("钉钉签名处理异常 " + e.getMessage());
        }
        return null;
    }
}
